package chatClient;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Hashtable;

import IChat.IChatServer;
import IChat.IChatter;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ChatClient extends Application {
	// 用户表
	Hashtable chatterHash = new Hashtable();
	// 用户名
	String name;
	// 服务器ip
	String serverIP;
	String targetChatterName = "全体用户";
	IChatter chatter;
	IChatServer server;
	// 连接窗口
	Stage connectStage = new ConnectStage(ChatClient.this);
	// 连接状态
	Label lbStatus = new Label("未连接");
	// 聊天输入区和聊天版
	TextArea taInput;
	TextArea taDisplay;
	Hashtable taDisplayHash = new Hashtable();
	Hashtable btnShinThreadpool = new Hashtable();
	ChatterListUtil clu;
	// 用户列表
	VBox chatterBox;
	VBox chatBox;
	@Override
	public void start(Stage primaryStage) throws Exception {
		try {
			try {
				chatter = new ChatterImpl(ChatClient.this);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
			clu = new ChatterListUtil(ChatClient.this);
			BorderPane root = new BorderPane();
			HBox topbar = new HBox();
			Button btnConnect = new Button("连接");
			topbar.getChildren().addAll(btnConnect);
			btnConnect.setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					connectStage.show();
				}
			});
			taDisplay = new TextArea();
			taInput = new TextArea();
			taInput.setOnKeyPressed(new EventHandler<KeyEvent>() {
				@Override
				public void handle(KeyEvent keyEvent) {
					if (keyEvent.getCode() == KeyCode.ENTER) {
						sendMessage();
						taInput.setText("");
					}
				}
			});
			taDisplay.setPrefWidth(500);
			taDisplay.setPrefHeight(350);
			taDisplay.setWrapText(true);
			taDisplay.setEditable(false);
			taDisplay.intersects(5, 5, 5, 5);

			taInput.setPrefWidth(500);
			taInput.setPrefHeight(100);
			taInput.setWrapText(true);
			taInput.setEditable(false);
			taInput.intersects(5, 5, 5, 5);
			chatBox = new VBox();
			chatterBox = new VBox();
			Button btnMsgAll = new Button("全体用户");
			btnMsgAll.setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					targetChatterName = "全体用户";
					chatBox.getChildren().remove(0);
					chatBox.getChildren().add(0, taDisplay);
				}
			});
			chatterBox.getChildren().add(btnMsgAll);
			chatBox.getChildren().addAll(taDisplay, taInput);
			ScrollPane chatterPane = new ScrollPane(chatterBox);
			root.setLeft(chatterPane);
			root.setCenter(chatBox);
			root.setTop(topbar);
			root.setBottom(lbStatus);
			Scene scene = new Scene(root, 640, 480);
			primaryStage.setScene(scene);
			primaryStage.setTitle("wetalk!");
			primaryStage.setResizable(true);
			primaryStage.show();
			primaryStage.setOnCloseRequest(e -> {
				Platform.runLater(new Runnable() {
				    @Override
				    public void run() {
				    	exit();
				    }
				});
			});
			
			// 组件测试
			// ChatterListUtil.addChatter(chatterBox, "4534");
			// ChatterListUtil.removeChatter(chatterBox, "全体用户");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		launch(args);
	}

	public void connect() throws RemoteException, MalformedURLException, NotBoundException {
		server = (IChatServer) Naming.lookup("//" + serverIP + "/ChatServer");
		// System.out.println(server);
		server.login(name, chatter);
	}

	private void exit() {
		destroy();
		System.exit(0);
	}

	public void destroy() {
		try {
			disconnect();
		} catch (RemoteException ex) {
			ex.printStackTrace();
		}
	}

	protected void disconnect() throws RemoteException {
		if (server != null)
			server.logout(name);
	}

	public void serverStop() {
		display("服务器停止");
		server = null;
		chatterHash.clear();
		lbStatus.setText("未连接");
	}

	public void connectAction() {

		try {
			connect();
			lbStatus.setText(name + "已连接服务器：" + serverIP);
			taInput.setEditable(true);
			taDisplay.setText("");
		} catch (RemoteException | MalformedURLException | NotBoundException e) {
			e.printStackTrace();
			lbStatus.setText("连接服务器失败");
		}

	}

	public void receiveEnter(String name, IChatter chatter, boolean hasEntered) {
		if (name != null && chatter != null) {
			chatterHash.put(name, chatter);
			TextArea newtaDisplay = new TextArea();
			taDisplayHash.put(name, newtaDisplay);
			if (!name.equals(this.name)) {
				if (!hasEntered)
					display(name + " 进入聊天室");
				Platform.runLater(new Runnable() {
				    @Override
				    public void run() {
				    	clu.addChatter(name);
				    }
				});
			}
		}
	}

	public void receiveExit(String name) {
		if (name != null && chatter != null) {
			chatterHash.remove(name);
			taDisplayHash.remove(name);
			BtnShinningThread th = (BtnShinningThread)btnShinThreadpool.get(name);
			th.stop();
			btnShinThreadpool.remove(name);
		}
		Platform.runLater(new Runnable() {
		    @Override
		    public void run() {
		    	clu.removeChatter(name);
		    }
		});
		display(name + " 离开聊天室");
	}

	public void receiveChat(String name, String message) {
		display(name + ": " + message);
	}

	public void receiveWhisper(String name, String message) {
//		display(name + " 私聊: " + message);
		TextArea ta = (TextArea)taDisplayHash.get(name);
		ta.appendText(name + "私聊: " + message + '\n');
		createButtonCalling(name);
		setButtonCallingOn(name);
	}
	
	public void setButtonCallingOn(String name){
		if(!name.equals(targetChatterName)){
			BtnShinningThread th = (BtnShinningThread)btnShinThreadpool.get(name);
			th.flag = true;
		}
	}
	
	public void setButtonCallingOff(String name){
		if(name.equals(targetChatterName)){
			BtnShinningThread th = (BtnShinningThread)btnShinThreadpool.get(name);
			if(th != null){
				th.flag = false;
			}
		}
	}
	
	public void createButtonCalling(String name){
		if(btnShinThreadpool.get(name) == null){
			for(int i=0; i<chatterBox.getChildren().size(); i++){
				if(((Button)chatterBox.getChildren().get(i)).getText().equals(name)){
					Button btn = (Button)chatterBox.getChildren().get(chatterBox.getChildren().size()-1);
						BtnShinningThread btnTh = new BtnShinningThread(btn);
				    	btnShinThreadpool.put(btn.getText(), btnTh);
				    	btnTh.start();
				}
			}
		}
	}
	
//	class BtnShinningThread extends Thread{
//		Button btn;
//		boolean flag = false;
//		BtnShinningThread(Button btn){
//			this.btn = btn;
//		}
//		@Override
//		public void run() {
//			while(true){
//				try {
//					if(flag){
//						btn.setStyle("-fx-base: #ee2211;");
//						Thread.sleep(500);
//						btn.setStyle(STYLESHEET_CASPIAN);
//					}
//					btn.setStyle(STYLESHEET_CASPIAN);
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//		
//	}

	private void display(String s) {
		if (!s.endsWith("\n")) {
			taDisplay.appendText(s + "\n");
		} else {
			taDisplay.appendText(s);
		}

		int length = taDisplay.getText().length() - 1;
		taDisplay.selectRange(length, length);
	}

	private void sendMessage() {
		String message = taInput.getText();
		if (message != null && message.length() > 0) {
			taInput.setText("");
			// taInput.setCaretPosition(0);
			taInput.positionCaret(0);
			if (server != null) {
				if ("全体用户".equals(targetChatterName)) {// 发送给所有用户
					try {
						display(name + ":" + message);
						server.chat(name, message);
					} catch (RemoteException ex) {
						ex.printStackTrace();
					}
				} else {// 私聊，发给所选用户
					IChatter targetChatter = (IChatter) chatterHash.get(targetChatterName);
					try {
						TextArea mytargetArea = (TextArea)taDisplayHash.get(targetChatterName);
						mytargetArea.appendText(this.name + ": " + message + '\n');
						targetChatter.receiveWhisper(name, message);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
		}
		taInput.requestFocus();
		taInput.clear();
	}

}
